package com.lanmon.dao;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;

import com.lanmon.pojo.Exam;
import com.lanmon.sqlite.DefaultResultSetHandler;
import com.lanmon.sqlite.ExamResultSetHandler;
import com.lanmon.sqlite.SqliteConnection;

public class ExamDao {
	private Connection connection = SqliteConnection.getConnection();
	private QueryRunner runner = new QueryRunner();
	
	/**
	 * 根据主键ID查询记录
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public Exam queryById(int id) throws Exception {
		return runner.query(connection, "select * from exam where id = ?", new ExamResultSetHandler(), id);
	}
	
	/**
	 * 查询全部结果集
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<Exam> queryAll() throws Exception {
		return runner.query(connection, "select * from exam", new DefaultResultSetHandler());
	}
	
	/**
	 * 根据like 条件查询 //"select * from exam where title like ? or body like ?"
	 * 
	 * @param a
	 * @return
	 * @throws Exception
	 */
	public List<Exam> queryByWhere(String sql, Object[] a) throws Exception {
		return runner.query(connection, sql, new DefaultResultSetHandler(), a);
	}
	
	/**
	 * 根据主键删除记录
	 * 
	 * @param id
	 * @return true 删除成功
	 * @throws Exception
	 */
	public boolean deleteById(int id) throws Exception {
		return runner.update(connection, "delete from exam where id = ?", id) == 1;
	}
	
	/**
	 * 根据主键修改记录
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public boolean updateById(String[] values, int id) throws Exception {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < values.length; i++)
			list.add(values[i]);
		list.add(id + "");
		return runner.update(connection, "update exam set title = ?, body = ?, answer = ? where id = ?", list.toArray()) == 1;
	}
	
	/**
	 * 保存数据
	 * 
	 * @param values
	 * @return
	 * @throws Exception
	 */
	public int save(Object[] values) throws Exception {
		return runner.update(connection, "insert into exam (title,body,answer) values(?,?,?)", values);
	}
}
